package com.ljc.serch.service.impl;

import com.ljc.serch.service.Isearchservice;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.search.suggest.SuggestBuilder;
import org.elasticsearch.search.suggest.SuggestBuilders;
import org.elasticsearch.search.suggest.completion.CompletionSuggestion;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Service
public class SearchService implements Isearchservice {

    @Autowired
    private RestHighLevelClient restHighLevelClient;
    @Override
    public List<Object> getSuggestion(String prefix) {
        //1.准备Request
        try {
            SearchRequest request = new SearchRequest("item");
            //2.准备dsl
            request.source().fetchSource(new String[0],null);
            request.source().suggest(new SuggestBuilder().addSuggestion("my_suggestion",
                    SuggestBuilders.completionSuggestion("suggestion").size(10).skipDuplicates(true).prefix(prefix)));

            //3.发送请求
            SearchResponse response = restHighLevelClient.search(request, RequestOptions.DEFAULT);
            //4.解析结果
            //4.1获取suggestion
            CompletionSuggestion suggestion = response.getSuggest().getSuggestion("my_suggestion");
            //4.2获取options
            List<CompletionSuggestion.Entry.Option> options = suggestion.getOptions();
            //4.3循环遍历，
            List<Object> list = new ArrayList<>(options.size());
            for (CompletionSuggestion.Entry.Option option: options) {
                list.add(option.getText().string());
            }
            return list;
        } catch (IOException e) {

          throw new RuntimeException(e);
        }
    }
}
